package util;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Map;

public class BeanUtils {
    public static <T> T parameterEncapsulation(Class<T> cls, HttpServletRequest request) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        T t = null;
        try {
            t = cls.getDeclaredConstructor().newInstance();
            Map<String, String[]> parameterMap = request.getParameterMap();
            Method[] methods = cls.getMethods();
            ArrayList<Method> setMethods = new ArrayList<>();
            for (Method method : methods) {
                if (method.getName().startsWith("set")) {
                    setMethods.add(method);
                }
            }
            String key = null;
            String value = null;
            String methodName = null;
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                methodName = "set" + entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1);
                key = entry.getKey();
                String values[] = entry.getValue();
                if (values != null && values.length > 0) {
                    value = values[0];
                }
                for (Method setMethod : setMethods) {
                    if (methodName.equalsIgnoreCase(setMethod.getName())) {
                        Class<?>[] parameterTypes = setMethod.getParameterTypes();
                        String parameterTypeName = parameterTypes[0].getTypeName();
                        if (value != null && "" != value) {
                            if (parameterTypeName.equals("int") || parameterTypeName.equals("java.lang.Integer")) {
                                setMethod.invoke(t, Integer.parseInt(value));
                            } else setMethod.invoke(t, value);
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }
}
